/**
 * @author Created by qiush on 2017-06-21.
 */

const resourceUtil = require('./resourceUtil');

// CSS 中使用图片的正则
const REG_IMAGE_URL = /url\((["']?)([^"')]+)\1\)/i;

function _findViewResources(view) {
  const viewResources = {};

  const urls = _findViewResourceUrls(view);
  urls.forEach(url => {
    const resource = resourceUtil.getResourceFromUrl(url);
    if (resource) {
      viewResources[resource.name] = resource.resource;
    }
  });

  if (view.children && view.children.length > 0) {
    view.children.forEach(childView => {
      const childViewResources = _findViewResources(childView);
      Object.assign(viewResources, childViewResources);
    });
  }

  return viewResources;
}

function _findViewResourceUrls(view) {
  const urls = [];

  if (view.attrVals.src) {
    urls.push(view.attrVals.src);
  }

  const backgroundImage = _findStyleUrl(view.style.backgroundImage) || _findStyleUrl(view.style.background);
  if (backgroundImage) {
    urls.push(backgroundImage);
  }

  return urls;
}

function _findStyleUrl(style) {
  if (!style) {
    return null;
  }
  const match = style.match(REG_IMAGE_URL);
  if (match && match.length > 2) {
    return match[2];
  }
  return null;
}

const designResourceUtil = {
  findDesignResources(design) {
    const resources = _findViewResources(design.root);
    const cssResource = resourceUtil.getResourceFromUrl(`str://${design.id}.css`);
    resources[cssResource.name] = cssResource.resource;
    return resources;
  },

  _findViewResources(view) {
    return _findViewResources(view);
  }
};

module.exports = designResourceUtil;
